package com.xmkj.winmoney.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.common.base.Config;
import com.common.bean.MoneyCarBean;
import com.common.carbean.ThreePayBean;
import com.common.cons.Constans;
import com.common.mvp.BaseMvpActivity;
import com.common.mvp.BasePresenter;
import com.common.retrofit.entity.bean.YouHuiJuanBean;
import com.common.retrofit.methods.GetMoneyMethods;
import com.common.retrofit.methods.ThreePayMethods;
import com.common.retrofit.methods.YuePayMethods;
import com.common.retrofit.subscriber.CommonSubscriber;
import com.common.retrofit.subscriber.SubscriberListener;
import com.common.rxbus.RxBus;
import com.common.rxbus.postevent.RxKeyEvent;
import com.common.utils.EmptyUtils;
import com.common.utils.SPUtils;
import com.xgr.easypay.EasyPay;
import com.xgr.easypay.alipay.AliPay;
import com.xgr.easypay.alipay.AlipayInfoImpli;
import com.xgr.easypay.callback.IPayCallback;
import com.xgr.easypay.wxpay.WXPay;
import com.xgr.easypay.wxpay.WXPayInfoImpli;
import com.xmkj.winmoney.R;
import com.xmkj.winmoney.mine.activity.ChongZhiActivity;
import com.xmkj.winmoney.mine.activity.MyCardActivity;
import com.xmkj.payandlogin.ShareConfig;
import com.xmkj.payandlogin.ShareManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * Created by Administrator on 2018/4/8.
 */

public class PayActivity extends BaseMvpActivity {
    public static final String TOTAL = "total";
    public static final String ORDERID = "orderid";
    @BindView(R.id.iv_weichat)
    ImageView ivWeichat;
    @BindView(R.id.iv_alipay)
    ImageView ivAlipay;
    @BindView(R.id.iv_yue)
    ImageView ivYue;
    @BindView(R.id.rb1)
    RadioButton rb1;
    @BindView(R.id.rb2)
    RadioButton rb2;
    @BindView(R.id.rb3)
    RadioButton rb3;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.tv_pay)
    TextView tvPay;
    @BindView(R.id.tv_zhekou)
    TextView tv_zhekou;
    @BindView(R.id.tv_use)
    TextView tv_use;
    @BindView(R.id.tv_money)
    TextView tv_money;

    private int payType = 2;
    private String couponid = "";
    private String currenMoney;
    private String total;
    private String orderid;

    @Override
    protected BasePresenter createPresenterInstance() {
        return null;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void onViewCreated() {
        total = getIntent().getStringExtra(TOTAL);
        orderid = getIntent().getStringExtra(ORDERID);
    }

    @Override
    protected void doLogicFunc() {
        ShareConfig config = ShareConfig.instance()
                .qqId(Config.APP_QQ_ID)
                .wxSecret(Config.APP_SERECET)
                .wxId(Config.APP_ID);
        ShareManager.init(config);
        radioGroup.check(rb1.getId());
        gotoGetMoney();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                switch (checkedId) {
                    case R.id.rb1:
                        payType = 2;  // 微信
                        break;
                    case R.id.rb2:
                        payType = 1;  //支付宝
                        break;
                    case  R.id.rb3:
                        payType = 3;
                        break;
                }
            }
        });
        attachClickListener(tvPay);
        attachClickListener(tv_use);
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.USE_JUAN) && EmptyUtils.isNotEmpty(rxKeyEvent.getValue())) {
                    YouHuiJuanBean.ListsBean infobean = (YouHuiJuanBean.ListsBean) rxKeyEvent.getValue();
                    couponid = infobean.id+"";
                    tv_zhekou.setText("折扣"+infobean.rate+"%");
                }
            }
        }));
        rxManager.add(RxBus.getDefault().toObservable(RxKeyEvent.class).subscribe(new Action1<RxKeyEvent>() {
            @Override
            public void call(RxKeyEvent rxKeyEvent) {
                if (EmptyUtils.isNotEventEmpty(rxKeyEvent, RxKeyEvent.MONEY_CHANGE)&&(Boolean) rxKeyEvent.getValue()) {
                    gotoGetMoney();

                }
            }
        }));


    }
    private void gotoGetMoney() {
        CommonSubscriber<MoneyCarBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                MoneyCarBean infoBean = (MoneyCarBean) o;
                dismissProgressDialog();
                tv_money.setText(infoBean.account);
                currenMoney = infoBean.account;
            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        GetMoneyMethods.getInstance().orderinfo(subscriber, SPUtils.getShareInt(Constans.UID), SPUtils.getShareString(Constans.HASHID),SPUtils.getShareString(Constans.DETAILS_ID));
        rxManager.add(subscriber);
    }
    @Override
    protected void onViewClicked(View view) {
        if(view.getId()==tvPay.getId()){
//            gotoActivity(PingJiaActivity.class);
            if(payType==2||payType==1){ //微信支付
                gotoMakeOrderInfo();
            }else if(payType==3){
                gotoYuePay();
            }
        } else if(view.getId()==tv_use.getId()){
            Intent intent = new Intent(context, MyCardActivity.class);
            intent.putExtra(MyCardActivity.FROM_PAY,"pay");
            startActivity(intent);
        }
    }

    private void gotoYuePay() {
        if(Double.valueOf(total)>Double.valueOf(currenMoney)){
            showTwoDialog("提示", "账户余额不足", "去充值", "取消");
            setOnDialogViewClick(new OnDialogViewClick() {
                @Override
                public void leftViewClick() {
//                        showToastMsg("hha");
                 gotoActivity(ChongZhiActivity.class);
                }

                @Override
                public void singleViewClick() {

                }
            });
            return;
        }
        showProgressingDialog();
        CommonSubscriber<Object> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                dismissProgressDialog();
                gotoPingJia();
                showToastMsg("支付成功");
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.ORDER_STATUS_CHANGE, true));



            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        YuePayMethods.getInstance().accountPay(subscriber,uid,hashid,orderid, couponid);
        rxManager.add(subscriber);
    }

    private void gotoMakeOrderInfo() {
        showProgressingDialog();
        CommonSubscriber<ThreePayBean> subscriber = new CommonSubscriber<>(new SubscriberListener() {
            @Override
            public void onNext(Object o) {
                ThreePayBean infoBean = (ThreePayBean) o;
                dismissProgressDialog();
                if(EmptyUtils.isEmpty(infoBean.alipay)){
                    wxpayYj(infoBean.wxpay);
                }else {
                    alipayYJ(infoBean.alipay);
                }



            }

            @Override
            public void onError(String e, int code) {
                dismissProgressDialog();
                showToastMsg(e);
            }
        });

        ThreePayMethods.getInstance().pay_order(subscriber,uid,hashid,orderid,payType, couponid);
        rxManager.add(subscriber);
    }

    private void wxpayYj(List<ThreePayBean.WxpayEntity> bean) {
        //实例化微信支付策略
        String wxAppId = Config.APP_ID;
        WXPay wxPay = WXPay.getInstance((Activity) context, wxAppId);
        //构造微信订单实体。一般都是由服务端直接返回。
        WXPayInfoImpli wxPayInfoImpli = new WXPayInfoImpli();
        wxPayInfoImpli.setTimestamp(bean.get(0).timestamp + "");
        wxPayInfoImpli.setSign(bean.get(0).sign);
        wxPayInfoImpli.setPrepayId(bean.get(0).prepayid);
        wxPayInfoImpli.setPartnerid(bean.get(0).partnerid);
        wxPayInfoImpli.setAppid(Config.APP_ID);
        wxPayInfoImpli.setNonceStr(bean.get(0).noncestr);
        wxPayInfoImpli.setPackageValue(bean.get(0).packageX);
        //策略场景类调起支付方法开始支付，以及接收回调。
        EasyPay.pay(wxPay, (Activity) context, wxPayInfoImpli, new IPayCallback() {
            @Override
            public void success() {
//                onBackPressed();
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.ORDER_STATUS_CHANGE, true));
                showToastMsg("支付成功");
                gotoPingJia();
            }

            @Override
            public void failed() {
                showToastMsg("支付失败");

            }

            @Override
            public void cancel() {
                showToastMsg("支付取消");
            }
        });

    }

    private void gotoPingJia() {
        Intent intent = new Intent(context ,PingJiaActivity.class);
        intent.putExtra(PingJiaActivity.ORDERID,orderid);
        startActivity(intent);
    }

    private void alipayYJ(String payInfo) {
        //实例化支付宝支付策略
        AliPay aliPay = new AliPay();
        //构造支付宝订单实体。一般都是由服务端直接返回。
        AlipayInfoImpli alipayInfoImpli = new AlipayInfoImpli();
        alipayInfoImpli.setOrderInfo(payInfo);
        //策略场景类调起支付方法开始支付，以及接收回调。
        EasyPay.pay(aliPay, (Activity) context, alipayInfoImpli, new IPayCallback() {
            @Override
            public void success() {
                showToastMsg("支付成功");
//                onBackPressed();
                RxBus.getDefault().postSticky(new RxKeyEvent(RxKeyEvent.ORDER_STATUS_CHANGE, true));
                gotoPingJia();
            }

            @Override
            public void failed() {
                showToastMsg("支付失败");
            }

            @Override
            public void cancel() {
                showToastMsg("支付取消");
            }
        });
    }
    @Override
    protected void setNavigation() {
        setNavigationBack("支付");
    }



    @Override
    public void bindKnife() {
        ButterKnife.bind(this);

    }
}
